<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="username" label="用户名" left-icon="user-o" placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" clearable />
        <van-field v-model="password" type="password" name="password" label="密码" left-icon="shield-o" placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"  clearable/>
        <van-field v-model="code" type="code" name="code" label="验证码" left-icon="coupon-o" placeholder="请输入验证码"
          :rules="[{ required: true, message: '请填写验证码' }]" clearable>
          <template #button>
            <van-image @click="init()" width="80" height="40" :src="imgUrl" />
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" color="#4A90E2">
          登录
        </van-button>
      </div>
    </van-form>
    <div style="display: flex;justify-content: center;">
      <router-link to="/register" class="link">没有账号？点击注册</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant'
import { useRouter } from 'vue-router';
import { login, verificationCode } from '@/apis/auth'

const router = useRouter();
const username = ref('');
const password = ref('');
const code = ref('');
const imgUrl = ref('');

const onSubmit = async (values) => {
  const {data='',code,msg=''} =  await login({
    ...values,
    roles:'ROLE_USER'
  });
  if (code !== 200) {
    showToast(msg);
    return;
  }
  if (code === 200) {
    showToast('登录成功');
    localStorage.setItem('token', data);
    router.push('/home');
    return;
  }

};

const init = async () => {
  const { data = {} } = await verificationCode();
  imgUrl.value = data?.captcherImg
}

onMounted(() => {
  init()
})
</script>

<style lang="less" scoped>
.login {
  margin-top: 48px;
}
.link{
  color: #4A90E2;
}
</style>
